<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表表格区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showDialog(scope.row)"></el-button>
            <!-- 删除按钮 -->
            <el-button @click="deleteUser(scope.row.id)" type="danger" size="mini" icon="el-icon-delete"></el-button>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button @click="setRole(scope.row)" type="warning" size="mini" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10, 15]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="dialogClose">
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="ediitDialogClose">
        <el-form ref="editFormRef" :rules="editRules" :model="editFormData" label-width="80px">
          <el-form-item label="用户名：">
            <el-input disabled v-model="editFormData.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="editFormData.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model="editFormData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </span>
      </el-dialog>
       <!-- 分配角色对话框 -->
      <el-dialog @close="setRoleClose" title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
        <p>当前的用户：{{currentUser.username}}</p>
        <p>当前的角色：{{currentUser.role_name}}</p>
        <div>
          分配新角色：
              <el-select v-model="selectValue" placeholder="请选择">
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoleSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'user',
  data () {
    var checkEmail = (rules, value, callback) => {
      var reg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/
      if (!reg.test(value)) return callback(new Error('邮箱不合法！'))
      return callback()
    }
    var checkMobile = (rules, value, callback) => {
      var reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
      if (!reg.test(value)) return callback(new Error('手机号码不合法！'))
      return callback()
    }
    return {
      // 选择框选择的值
      selectValue: '',
      // 查询数据
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前没有显示多少数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框
      addDialogVisible: false,
      // 添加用户的form对象
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑对话框
      editDialogVisible: false,
      // 编辑对话框Form表单数据
      editFormData: {
        username: '',
        email: '',
        mobile: '',
        id: 0
      },
      // 编辑对话框中form表单的验证规则
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色的对话框
      setRoleDialogVisible: false,
      // 当前的用户角色信息
      currentUser: {},
      // 角色列表
      roles: []
    }
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.errror('获取用户列表失败！')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值 改变事件
    handleCurrentChange (newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getUserList()
    },
    // switch 开关控制
    async switchChange (val) {
      const { data: res } = await this.$axios.put(`users/${val.id}/state/${val.mg_state}`)
      if (res.meta.status !== 200) {
        this.$message.errror('更新用户状态失败！')
        val.mg_state = !val.mg_state
        return
      }
      this.$message.success('更新用户状态成功！')
    },
    // 对话框关闭事件
    dialogClose () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 提交添加用户数据
    submitForm () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请先填写表单信息')
        }
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败！')
        this.$message.success('提交成功！')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 编辑按钮对话框
    showDialog (val) {
      // 修改编辑对话框的显示
      this.editDialogVisible = true
      //  将编辑对话框的form表单数据和scope.row传过来的参数进行数据赋值
      this.editFormData = val
    },
    // 监听编辑对话框的关闭事件
    ediitDialogClose () {
      // 关闭编辑对话框时，重置编辑表单数据
      this.$refs.editFormRef.resetFields()
    },
    // 编辑对话框的form表单提交事件
    submitEditForm () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请正确填写表单数据！')
        const { data: res } = await this.$axios.put('users/' + this.editFormData.id, { mobile: this.editFormData.mobile, email: this.editFormData.email })
        if (res.meta.status !== 200) return this.$message.error('修改失败！')
        this.$message.success('修改用户信息成功！')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    deleteUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message.success('删除成功!')
        this.getUserList()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 分配权限
    async setRole (row) {
      this.setRoleDialogVisible = true
      this.currentUser = row
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取用户权限列表失败！')
      this.roles = res.data
    },
    // 设置权限发起请求
    async setRoleSubmit () {
      if (!this.selectValue) return this.$message('请选择角色！')
      const { data: res } = await this.$axios.put('users/' + this.currentUser.id + '/role', {
        rid: this.selectValue
      })
      if (res.meta.status !== 200) return this.$message.error('设置失败！')
      this.$message.success('设置成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
      this.selectValue = ''
    },
    // 关闭设置对话框
    setRoleClose () {
      this.setRoleDialogVisible = false
      this.selectValue = ''
      console.log(23)
    }
  },
  created () {
    // 页面加载完成请求用户信息
    this.getUserList()
  }
}
</script>

<style lang='less' scoped>

</style>
